package persistence.sqlsession;

import persistence.bean.Configuration;
import persistence.bean.MappedStatement;

import java.lang.reflect.*;
import java.util.List;

public class DefaultSqlSession implements SqlSession {
    private Configuration configuration;

    public DefaultSqlSession(Configuration configuration){
        this.configuration = configuration;
    }

    public <E> List<E> selectList(String statementId, Object... params) throws Exception {
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
        return new SampleExecutor().query(configuration, mappedStatement, params);
    }

    public <E> E selectOne(String statementId, Object... params) throws Exception {
        List<E> objects = selectList(statementId, params);
        E obj = null;
        if (objects.size() == 1) {
            obj = objects.get(0);
        } else {
            throw new RuntimeException("查询结果不为1");
        }
        return obj;
    }

    public <E> E getMapper(Class<?> mapperClass) {
        Object instance = Proxy.newProxyInstance(DefaultSqlSession.class.getClassLoader(), new Class[]{mapperClass}, new InvocationHandler() {
            //  proxy 代理对象，method 具体方法 ，args 参数
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                // namespace
                String methodName = method.getName();
                String className = method.getDeclaringClass().getName();
                String statementId = className + "." + methodName;
                // 根据返回值获取需要调用的方法
                Type returnType = method.getGenericReturnType();
                if (returnType instanceof ParameterizedType) {
                    selectList(statementId, args);
                } else {
                    selectOne(statementId, args);
                }

                return null;
            }
        });
        return (E) instance;
    }
}
